package com.hamll.geteway.filters;

import com.hamll.geteway.config.AuthProperties;
import com.hamll.geteway.utils.JwtTool;
import com.hmall.common.exception.UnauthorizedException;
import com.hmall.common.utils.CollUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@RequiredArgsConstructor
public class AutoGlobalFilter implements GlobalFilter, Ordered {

    private final JwtTool jwtTool;

    private final AuthProperties authProperties;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取Request
        ServerHttpRequest request = exchange.getRequest();
        // 2.判断是否不需要拦截
        if(isExclude(request.getPath().toString())){
            return chain.filter(exchange);
        }
        // 3.获取请求头中的token
        String token = null;
        // 一个请求头的键名可能对应多个键值，所以获取到的是集合
        List<String> authorizationHeaders = request.getHeaders().get("authorization");
        if(!CollUtils.isEmpty(authorizationHeaders)){
            token = authorizationHeaders.get(0);
        }
        // 4.校验并解析token
        Long userId = null;
        try{
            userId = jwtTool.parseToken(token);
        }catch(UnauthorizedException ex){
            // 如果无效，拦截
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        // TODO 5.如果有效，传递用户信息
        String userInfo = userId.toString();
        exchange.mutate()
                .request(b->b.header("user-info", userInfo))
                .build();

        // 6.放行
        return chain.filter(exchange);
    }

    private boolean isExclude(String antPath) {
        for (String pathPattern : authProperties.getExcludePaths()) {
            // pathPattern就是/search/**这种格式的路径，需要用AntPathMatcher类来对比
            // antPathMatcher.match(路径pattern, 路径)
            if(antPathMatcher.match(pathPattern, antPath)){
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
